package ping

import (
	"bytes"
	"os/exec"
	"regexp"
	"runtime"
	"strings"

	"github.com/spf13/cast"
	"golang.org/x/text/encoding/simplifiedchinese"
	"golang.org/x/text/transform"
)

func (p *Ping) Cmd(host string, count int) (error, int) {
	if count <= 0 {
		count = p.PingCount
	}
	loss := 100
	var args []string
	if runtime.GOOS == "windows" {
		args = append(args, "-n", cast.ToString(count), host)
	} else {
		args = append(args, "-c", cast.ToString(count), host)
	}
	cmd := exec.Command("ping", args...)
	output, err := cmd.CombinedOutput()
	if err != nil {
		return err, loss
	}
	outStr := string(output)
	if runtime.GOOS == "windows" {
		reader := transform.NewReader(bytes.NewReader(output), simplifiedchinese.GBK.NewDecoder())
		buf := new(bytes.Buffer)
		buf.ReadFrom(reader)
		outStr = buf.String()
	}
	for _, line := range strings.Split(outStr, "\n") {
		// 中文丢包率
		if strings.Contains(line, "丢失 =") && strings.Contains(line, "% 丢失") {
			re := regexp.MustCompile(`\((\d+)% 丢失\)`)
			match := re.FindStringSubmatch(line)
			if len(match) == 2 {
				loss = cast.ToInt(match[1])
			}
		}
		// 英文丢包率
		if strings.Contains(line, "Lost =") && strings.Contains(line, "% loss") {
			re := regexp.MustCompile(`\((\d+)% loss\)`)
			match := re.FindStringSubmatch(line)
			if len(match) == 2 {
				loss = cast.ToInt(match[1])
			}
		}
	}
	return nil, loss
}
